package main

import (
	"context"
	"encoding/json"
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
	"xin-job/admin/abiz"
	"xin-job/core/biz"
)

func main() {
	Start()

	server := http.Server{Addr: ":8080"}
	http.HandleFunc("/", indexFunc)

	go func() {
		err := server.ListenAndServe()
		if err != nil {
			log.Printf("http server start failed, err %v\n", err)
		}
	}()

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)

	<-stop // 阻塞

	Stop()

	// 优雅地关闭服务器
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := server.Shutdown(ctx); err != nil {
		log.Printf("Server Shutdown: %v", err)

	}
	log.Println("Server gracefully stopped")
}

func indexFunc(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		index(w)
	} else {

		body, err := io.ReadAll(r.Body)
		if err != nil {
			r := biz.Return[string]{Code: 500, Msg: err.Error()}
			data, err := json.Marshal(r)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			w.Header().Set("Content-Type", "application/json")
			w.Write(data)
		}

		switch r.URL.Path {
		case "/api/callback":
			var param []*biz.HandleCallbackParam
			err = json.Unmarshal(body, &param)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			re := abiz.GetBizAdmin().Callback(param)
			data, err := json.Marshal(re)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			w.Header().Set("Content-Type", "application/json")
			w.Write(data)
		case "/api/registry":
			var registryParam biz.RegistryParam
			err = json.Unmarshal(body, &registryParam)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			re := abiz.GetBizAdmin().Registry(&registryParam)
			data, err := json.Marshal(re)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			w.Header().Set("Content-Type", "application/json")
			w.Write(data)
		case "/api/registryRemove":
			var registryParam biz.RegistryParam
			err = json.Unmarshal(body, &registryParam)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			re := abiz.GetBizAdmin().RegistryRemove(&registryParam)
			data, err := json.Marshal(re)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			w.Header().Set("Content-Type", "application/json")
			w.Write(data)
		default:
			index(w)
		}
	}
}

func index(w http.ResponseWriter) {
	var html = `
				<!DOCTYPE html>
				<html lang="en">
				<head>
					<meta charset="UTF-8" />
					<meta name="viewport" content="width=device-width, initial-scale=1.0" />
					<title>{{ . }}</title>
				</head>
				<body>
					xxl-job 页面使用了模版，扒页面有些麻烦。
				</body>
				</html>
	`
	t, _ := template.New("Index").Parse(html)
	_ = t.Execute(w, "xin-job")
}

